package Region;

import Region.socket.ClientSocketManager;
import Region.socket.MasterRegionCopyManager;
import Region.socket.MasterSocketManager;
import Region.socket.RegionToRegionSocketManager;

import java.io.IOException;

public class RegionManager {

    private ClientSocketManager clientSocketManager;
    private DatabaseManager dataBaseManager;
    private MasterSocketManager masterSocketManager;
    private ZookeeperServiceManager zookeeperManager;
    private LogManager logManager;
    private RegionToRegionSocketManager regionToRegionSocketManager;
    private MasterRegionCopyManager masterRegionCopyManager;

    private final int MASTER_PORT = 12345;
    private final int CLIENT_PORT = 6666;
    private final int REGION_PORT = 1221;
    private final int COPY_PORT = 7309;
    private final String REGION_IP = "10.193.250.18";
    private final String MASTER_IP = "10.193.250.18";

    public RegionManager() throws IOException, InterruptedException {
        dataBaseManager = new DatabaseManager();
        zookeeperManager = new ZookeeperServiceManager(REGION_IP, MASTER_IP);
        logManager = new LogManager();
        masterSocketManager = new MasterSocketManager(MASTER_IP, MASTER_PORT, REGION_PORT, dataBaseManager, logManager);
        clientSocketManager = new ClientSocketManager(COPY_PORT, CLIENT_PORT, masterSocketManager, dataBaseManager, logManager);
        regionToRegionSocketManager = new RegionToRegionSocketManager(REGION_PORT, dataBaseManager, logManager);
        masterRegionCopyManager = new MasterRegionCopyManager(COPY_PORT,masterSocketManager,dataBaseManager,logManager);
    }

    public void run() throws Exception {

        //注册zookeeper线程
        Thread zkServiceThread = new Thread(zookeeperManager);
        zkServiceThread.start();
        //创建与主节点通信的线程
        Thread MasterSocketThread = new Thread(masterSocketManager);
        MasterSocketThread.start();
        //创建与客户端通信的线程
        Thread clientCenterThread = new Thread(clientSocketManager);
        clientCenterThread.start();
        //创建Region相互之间的通信线程
        Thread regionThread = new Thread(regionToRegionSocketManager);
        regionThread.start();
        //创建主从复制通信线程
        Thread copyThread = new Thread(masterRegionCopyManager);
        copyThread.start();

//        logManager.createLog("t");
//        logManager.addLog("t","insert into t values (123)");
//        logManager.addLog("t","insert into t values (1234)");

//        masterSocketManager.handleCommand("<M2R>[5]","t,10.193.250.18");

        System.out.println("从节点开始运行！");
    }
}
